import 'dart:developer';

import 'package:flutter/material.dart';

class PageViewKeepAlivePage extends StatefulWidget {
  const PageViewKeepAlivePage({super.key});

  @override
  State<PageViewKeepAlivePage> createState() => _PageViewKeepAlivePageState();
}

class _PageViewKeepAlivePageState extends State<PageViewKeepAlivePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("PageViewKeepAlive"),
      ),
      body: PageView.builder(
        itemCount: 10,
        itemBuilder: (context, index) {
          // 在没有缓存的情况下，每次都会重新构建，执行build方法
          return MyContainer(num: index);
        },
      ),
    );
  }
}

class MyContainer extends StatefulWidget {
  final int num;
  const MyContainer({super.key, required this.num});

  @override
  State<MyContainer> createState() => _MyContainerState();
}

// 继承AutomaticKeepAliveClientMixin并重写wantKeepAlive方法可以缓存页面
class _MyContainerState extends State<MyContainer>
    with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    log("${widget.num}执行了一次build");
    return Center(
      child: Text("Day${widget.num}"),
    );
  }

  // 是否需要缓存，返回true表示需要缓存
  @override
  bool get wantKeepAlive => true;
}
